<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>虚拟dom练习</title>
</head>

<body>
    <!-- <div class="box" style="width: 500px;height: 300px;">
        <div class="box-top" style="background-color: palegoldenrod;">
            <div class="title">
                <span class="title-span">今天是周六</span>
                <p class="title-word">我在练习虚拟dom</p>
            </div>
        </div>
        <div class="box-bottom" style="background-color: palegreen;">
            <h1 class="box-bottom-title">下午干什么呢？</h1>
            <p class="box-bottom-word">学习react</p>
        </div>
    </div> -->
    <div id="app"></div>
</body>

</html>


<script>
    // 创建虚拟dom的方法
    const getDom = (target, props, children) => {
        return { target, props, children }
    }

    // 创建虚拟dom
    const newVdom = getDom(
        "div",
        {
            class: "box",
            style: "width: 500px;height: 300px;"
        },
        [
            getDom("div", { class: "box-top", style: "background-color: palegoldenrod;" }, [
                getDom("div", { class: "title" }, [
                    getDom("span", { class: "title-span" }, "今天是周六"),
                    getDom("p", { class: "title-word" }, "我在练习虚拟dom")
                ]),
            ]),
            getDom("div", { class: "box-bottom", style: "background-color: palegreen;" }, [
                getDom("span", { class: "box-bottom-title" }, "下午干什么呢？"),
                getDom("p", { class: "box-bottom-wodr" }, "学习react")
            ])
        ]
    )

    console.log(newVdom);

    // 创建真实dom节点
    const vDomToDom = (vDom) => {
        // 获取方法
        const { target, props, children } = vDom
        // 创建真实dom节点
        const dom = document.createElement(target)
        //设置属性
        for (i in props) {
            dom.setAttribute(i, props[i])
        }
        // 添加内容
        if (Array.isArray(children)) {
            children.forEach(item => {
                dom.appendChild(vDomToDom(item))
            })
        } else {
            dom.appendChild(document.createTextNode(children))
        }
        return dom
    }

    document.getElementById("app").appendChild(vDomToDom(newVdom))
</script>